import numpy as np
import shutil
import os
import SimpleITK as sitk
from nii_to_dcm_image import nifti2dicom_1file

def nii2dcm_single(nii_path):
    save_folder = nii_path.replace('nii_','dcm_').replace('.nii.gz','')                  
    # if not os.path.exists(save_folder):
    #     os.makedirs(save_folder)
        
    # ori_data = sitk.ReadImage(nii_path)  # 读取一个数据
    # data1 = sitk.GetArrayFromImage(ori_data)  # 获取数据的array
    # img_name = os.path.split(nii_path)  #分离文件名
    # img_name = img_name[-1]
    # img_name = img_name.split('.')
    # img_name = img_name[0]
    # i = data1.shape[0]
    # # 关键部分
    # castFilter = sitk.CastImageFilter()
    # castFilter.SetOutputPixelType(sitk.sitkInt16)
    # for j in range(0, i):   #将每一张切片都转为png 
    #   slice_i = data1[j, :, :]
    #   data_img = sitk.GetImageFromArray(slice_i)
    #   # Convert floating type image (imgSmooth) to int type (imgFiltered)
    #   data_img = castFilter.Execute(data_img)
    #   sitk.WriteImage(data_img, "%s/%s-%d.dcm" % (save_folder, img_name, j+1))
    nifti2dicom_1file(in_dir=nii_path, out_dir=save_folder)
      
  
source_path='./predictTCL/nii_samples'
folders=os.listdir(source_path)
for folder in folders:
  patient_folder=os.path.join(source_path,folder)
  modalities=os.listdir(patient_folder)
  for modality in modalities:
    nii_path=os.path.join(patient_folder,modality)
    nii2dcm_single(nii_path)
    
